package com.lantosec.hmrp.modules.workflow.listener;

import com.lantosec.hmrp.modules.sysdata.service.ISysDataProcessService;
import com.lantosec.hmrp.modules.sysdata.service.ISysDataProcessTaskService;
import com.lantosec.hmrp.modules.workflow.enumeration.ProcessStatusEnum;
import com.lantosec.hmrp.modules.workflow.enumeration.ProcessVariableEnum;
import lombok.extern.log4j.Log4j2;
import org.flowable.engine.TaskService;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 流程结束监听事件
 *
 * @author lichaowei
 * @date 2020/5/27
 */
@Component
@Log4j2
public class ProcessEndListener implements ExecutionListener {
    private static final long serialVersionUID = 1L;

    @Autowired
    private TaskService taskService;
    @Autowired
    private ISysDataProcessService sysDataProcessService;
    @Autowired
    private ISysDataProcessTaskService sysDataProcessTaskService;

    @Override
    public void notify(DelegateExecution delegateExecution) {
        String processInstanceId = delegateExecution.getProcessInstanceId();
        log.info("流程结束监听事件----->processInstanceId:" + processInstanceId);

        String userId = (String) delegateExecution.getVariable(ProcessVariableEnum.USER_ID.getCode());
        Task task = taskService.createTaskQuery().processInstanceId(processInstanceId).singleResult();
        //更新流程实例与数据的关系表,流程结束时间
        sysDataProcessService.updateProcess(processInstanceId, delegateExecution.getCurrentActivityId(), null
                , "流程结束", new Date(), ProcessStatusEnum.FINISH.getType(), null);

        // 获取节点自定义属性对象
        //CustomAttributeVO customAttributeVO = workflowRepositoryService.getCustomAttribute(task.getTaskDefinitionKey(), task.getProcessDefinitionId());
        sysDataProcessTaskService.insertTask(processInstanceId, "", userId, "", Boolean.FALSE);
    }
}
